package com.sudworth.repository.network.okhttp

import android.content.Context
import android.content.SharedPreferences
import com.sudworth.repository.network.HttpEngine
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author: shalei
 * @Date: 2019-10-31 14:24
 * @Desc:
 **/
class OkHttpEngine : HttpEngine {

    companion object {
        private const val DEFAULT_CONNECT_TIMEOUT = 30L
        private const val DEFAULT_WRITE_TIMEOUT = 30L
        private const val DEFAULT_READ_TIMEOUT = 30L

        private lateinit var mSp: SharedPreferences

        private var instance: OkHttpEngine? = null
            get() {
                if (field == null) {
                    field = OkHttpEngine()
                }
                return field
            }

        @JvmStatic
        fun get(sp: SharedPreferences): OkHttpEngine {
            mSp = sp
            return instance!!
        }
    }

    private var mOkHttpBuilder: OkHttpClient.Builder = OkHttpClient.Builder()

    init {
        mOkHttpBuilder.addInterceptor(HeaderInterceptor(mSp))
        mOkHttpBuilder.addInterceptor(NetWorkInterceptor(mSp))
        mOkHttpBuilder.addInterceptor(PostInterceptor())
        /**
         * 设置超时和重新连接
         */
        mOkHttpBuilder.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
        mOkHttpBuilder.readTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS)
        mOkHttpBuilder.writeTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)

        //错误重连
        mOkHttpBuilder.retryOnConnectionFailure(true)
    }

    override fun <T> create(service: Class<out T>, context: Context, baseUrl: String): T {
        mOkHttpBuilder.addInterceptor(CacheInterceptor(context))
        val retrofit = Retrofit.Builder()
            .client(mOkHttpBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .baseUrl(baseUrl)
            .build()
        return retrofit.create(service)
    }

    override fun getOkHttpClient(): OkHttpClient.Builder {
        return mOkHttpBuilder
    }

}